/**
 * Created by Tuffy on 16/6/6.
 */
'use strict';

adminCtrl

.controller('OrderCtrl', ['$rootScope', '$scope', '$state', 'OrderService', function ($rootScope, $scope, $state, OrderService) {
	
    $scope.page = {
        pageNo: 1,
        totalPage: 0
    };

    $scope.orderInfo = [];
    $scope.TichePicDate = [];

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            alreadystartList();
        }
    };

    // 初始化数据列表
    function loadData() {
        OrderService.list({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize
        }).success(function (result) {
            if (result.success) {
                $scope.orderInfo = result.data.orderInfo;
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    }
    
    // 查询订单状态 60已发车
    function alreadystartList(){
    	OrderService.alreadystartList({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize
        }).success(function (result){
    			if(result.success){
    				$scope.orderInfo = result.data.orderInfo;
    				$scope.page = result.data.page;
    				buildPage();
    			} else{
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
    			}
    		})
    }
    
    alreadystartList();
}])

.controller('OrderComCtrl', ['$rootScope', '$scope', '$state', 'OrderService', function ($rootScope, $scope, $state, OrderService) {
	
    $scope.page = {
        pageNo: 1,
        totalPage: 0
    };

    $scope.orderInfo = [];
    $scope.TichePicDate = [];

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            completedList();
        }
    };

    // 初始化数据列表
    function loadData() {
        OrderService.list({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize
        }).success(function (result) {
            if (result.success) {
                $scope.orderInfo = result.data.orderInfo;
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    }
	
    // 查询订单状态 80已收车
    function completedList(){
    	OrderService.completedList({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize
        }).success(function (result){
    			if(result.success){
    				$scope.orderInfos = result.data.orderInfo;
    				$scope.page = result.data.page;
    				buildPage();
    			} else{
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
    			}
    		})
    }
	
    completedList();
}])

.controller('OrderPicCtrl', ['$rootScope', '$scope', '$state', 'OrderService', function ($rootScope, $scope, $state, OrderService) {

	var orderId = $state.params.orderId;
	
    function orderDriverstart(){
    	if(orderId){
    		OrderService.orderDriverstart(orderId)
    		.success(function (result) {
                if (result.success) {
                    $scope.TichePicDate = result.data;
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
    		});
    	}
    };
    
    // 后台确认发车
    $scope.changeStatus = function () {
        OrderService.changeStatus(orderId)
            .success(function (result) {
                if (result.success) {
                    $state.go("order", {}, {reload: true});
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
    }
	
	orderDriverstart();
}])
	
.controller('OrderDonepicCtrl', ['$rootScope', '$scope', '$state', 'FileUploader', 'OrderService', 'QiniuService', 'fileReader', function ($rootScope, $scope, $state, FileUploader, OrderService, QiniuService, fileReader) {

	var orderId = $state.params.orderId;
	// var myFile = $state.params.myFile;
	// var imageSrc = $state.params.imageSrc;
	
    function orderDonePic(){
    	if(orderId){
    		OrderService.orderDonePic(orderId)
    		.success(function (result) {
                if (result.success) {
                    $scope.TichePicDate = result.data;
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
    		});
    	}
    };
    
    // 后台确认收车，订单完成
    $scope.changeStatusOrderDone = function () {
        OrderService.changeStatusOrderDone(orderId)
            .success(function (result) {
                if (result.success) {
                    $state.go("order-completed", {}, {reload: true});
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
    }
    
    $scope.save = function() {
    	OrderService.uploadimg($scope.file.name, orderId)
        .success(function (result) {
            if (result.success) {
                $state.go("order-completed", {}, {reload: true});
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }
    	
    $scope.getFile = function () {
        fileReader.readAsDataUrl($scope.file, $scope)
	          .then(function(result) {
	              $scope.imageSrc = result;
	          });
    };
    
    // 上传照片
    $scope.uploadImgs = function () {
        var uploader = $scope.uploader = null;
        QiniuService.getUploadToken()
            .success(function (result) {
                if (result.success) {

                    // 交车单据
                    var imgKey = null;
                    var uploader = $scope.uploader = new FileUploader({
                        url: 'http://upload.qiniu.com/',
                        formData: [{
                            token: result.data
                        }],
                        queueLimit: 1
                    });

                    uploader.filters.push({
                        name: 'file',
                        fn: function(item /*{File|FileLikeObject}*/, options) {
                            var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                            return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
                        }
                    });

                    uploader.onSuccessItem = function(fileItem, response, status, headers) {
                        imgKey = response.key;
                    };

                    uploader.onCompleteAll = function() {
                        var index = layer.load(1, {
                            shade: [0.1, '#fff']
                        });
                        OrderService.uploadimg(orderId, Tools.constant.truckTicket, imgKey)
                            .success(function (result) {
                                if (result.success) {
                                    ($scope.TichePicDate.data || []).push({
                                        url: result.data.url,
                                        alt: '收车单据'
                                    });
                                    layer.msg('上传成功');
                                } else {
                                    layer.msg(result.message || '上传失败');
                                }
                            })
                        .finally(function () {
                            layer.close(index);
                        });
                    };

                    // 交车照片
                    var imgKey2 = null;
                    var uploader2 = $scope.uploader2 = new FileUploader({
                        url: 'http://upload.qiniu.com/',
                        formData: [{
                            token: result.data
                        }],
                        queueLimit: 1
                    });

                    uploader2.filters.push({
                        name: 'file',
                        fn: function(item /*{File|FileLikeObject}*/, options) {
                            var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                            return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
                        }
                    });

                    uploader2.onSuccessItem = function(fileItem, response, status, headers) {
                        imgKey2 = response.key;
                    };

                    uploader2.onCompleteAll = function() {
                        var index = layer.load(1, {
                            shade: [0.1, '#fff']
                        });
                        OrderService.uploadimg(orderId, Tools.constant.truckPic, imgKey2)
                            .success(function (result) {
                                if (result.success) {
                                    ($scope.TichePicDate.data || []).push({
                                        url: result.data,
                                        alt: '收车照片'
                                    });
                                    layer.msg('上传成功');
                                } else {
                                    layer.msg(result.message || '上传失败');
                                }
                            })
                        .finally(function () {
                            layer.close(index);
                        });
                    };
                }
            })
    };
    orderDonePic();

    // 上传照片初始化
    $scope.uploadImgs();
}])

// .directive('fileModel', ['$parse', function ($parse) {
//   return {
//     restrict: 'A',
//     link: function(scope, element, attrs, ngModel) {
//       var model = $parse(attrs.fileModel);
//       var modelSetter = model.assign;
//       element.bind('change', function(event){
// 	        scope.$apply(function(){
// 	          modelSetter(scope, element[0].files[0]);
// 	        });
// 	        //附件预览
// 	        scope.file = (event.srcElement || event.target).files[0];
// 	        scope.getFile();
//       });
//     }
//   };
// }])
//
// .factory('fileReader', ["$q", "$log", function($q, $log){
// 	  var onLoad = function(reader, deferred, scope) {
// 	    return function () {
// 	      scope.$apply(function () {
// 	        deferred.resolve(reader.result);
// 	      });
// 	    };
// 	  };
// 	  var onError = function (reader, deferred, scope) {
// 	    return function () {
// 	      scope.$apply(function () {
// 	        deferred.reject(reader.result);
// 	      });
// 	    };
// 	  };
// 	  var getReader = function(deferred, scope) {
// 	    var reader = new FileReader();
// 	    reader.onload = onLoad(reader, deferred, scope);
// 	    reader.onerror = onError(reader, deferred, scope);
// 	    return reader;
// 	  };
// 	  var readAsDataURL = function (file, scope) {
// 	    var deferred = $q.defer();
// 	    var reader = getReader(deferred, scope);
// 	    reader.readAsDataURL(file);
// 	    return deferred.promise;
// 	  };
// 	  return {
// 	    readAsDataUrl: readAsDataURL
// 	  };
// }])

.controller('OrdersAllController', ['$rootScope', '$scope', '$state', 'OrderService', function ($rootScope, $scope, $state, OrderService) {
	
    $scope.page = {
        pageNo: 1,
        totalPage: 0
    };
    
    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            loadData();
        }
    };

    // 初始化数据列表
    function loadData() {
        OrderService.list({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize
        }).success(function (result) {
            if (result.success) {
                $scope.orderInfo = result.data.orderInfo;
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    }
    
    loadData();
}])

.controller('OrderDetailController', ['$rootScope', '$scope', '$state', 'OrderService', function ($rootScope, $scope, $state, OrderService) {
    var orderId = $state.params.orderId;
    $scope.orderInfo = null;

    // 加载订单信息
    OrderService.orderDetail(orderId)
        .success(function (result) {
            if (result.success){
                $scope.orderInfo = result.data;
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
}])